package dunshan.textdemo

import io.gatling.core.Predef._
import io.gatling.http.Predef._

class ApplicationParam extends Simulation {
  val httpConf = http
    .baseUrl("http://127.0.0.1:8080") // Here is the root for all relative URLs
    .acceptHeader("application/json, text/plain, */*") // Here are the common headers
    .acceptLanguageHeader("zh-CN,zh;q=0.9,en;q=0.8")
    .acceptEncodingHeader("gzip, deflate, br")
    .userAgentHeader("Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1")

  val headersInfo = Map("Content-Type" -> "application/json") // note the headers specific to a given request

  val scn = scenario("SigningAdvisor")
    .exec(http("login")
      .post("/login/json") //test data
      .headers(headersInfo)
      .body(StringBody("""{ "userName": "7d","passWord":"123456"}""")).asJson
      .check(status.is(200))
      .check(jsonPath("$.data.userId").saveAs("userId"))
      .check(jsonPath("$.data.token").exists)
      .check(jsonPath("$.data.token").saveAs("token")) //获取响应结果并且保存起来
    )

    // 取出 token 值并修改
    .exec(session => {
      val token = session("token").as[String]
      val token2 = "Bearer " + token
      session.set("token", token2)
    })

    // 打印 session 验证正确性
    .exec { session =>
      println(session)
      session
    }

    //关联参数
    .exec(http("associated")
      .post("/token")
      .headers(headersInfo)
      .header("Authorization", "${token}") //获取上面修改的参数
      .body(StringBody("""{"userName": "${userId}"}""")).asJson)


  setUp(scn.inject(atOnceUsers(1)).protocols(httpConf))
}
